package com.imooc.o2o.web.shopadmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Area;
import com.imooc.o2o.entity.PersonInfo;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.entity.ShopCategory;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.service.AreaService;
import com.imooc.o2o.service.ShopCategoryService;
import com.imooc.o2o.service.ShopServce;
import com.imooc.o2o.util.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 徐老板
 * @date 2020/1/5   9:09
 */
@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {

    @Autowired
    private ShopServce shopServce;
    @PostMapping("/registershop")
    @ResponseBody
    private Map<String,Object> registerShop(HttpServletRequest request){
        //这个变量是用来向前端传送数据的 这个跟之前倒是不一样
        Map<String,Object> mapModel = new HashMap<>();

        /**
         * 这里首先是验证码的判断
         */
//        if (!CodeUtil.checkVerifyCode(request)){
//            mapModel.put("success",false );
//            mapModel.put("errMsg","验证码输入错误" );
//            return mapModel;
//        }

        /**
         *   处理前端传来数据 上面@responsebody注解的作用是把object类转换为json
         *   下面这个配合依赖jackson-databind可以把前端传过来的字符串转换为object对象
         */
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        ObjectMapper mapper=new ObjectMapper();
        //创建这个的目的是用来接收前端传过来的实体类（转化好的）
        //在转化的时候可能会出现转化不了的情况 这个时候需要try catch
        Shop shop=null;
        try {
                shop=mapper.readValue(shopStr,Shop.class );
            System.out.println("========="+shop);
        } catch (IOException e) {
            mapModel.put("success",false );
            mapModel.put("errMsg", e.getMessage());
            return mapModel;
        }

        CommonsMultipartFile shopImg= null;
        CommonsMultipartResolver commonsMultipartResolver= new CommonsMultipartResolver(request.getServletContext());
        if (commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest= (MultipartHttpServletRequest) request;
            //这一步是从前端的file文件上口获取数据
            shopImg= (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }else {
            mapModel.put("success",false );
            mapModel.put("errMsg","上传图片不能为空" );
            return mapModel;
        }

        //注册店铺
        if (shop!=null&&shopImg !=null){
            PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
            //session TODO
            shop.setOwner(owner);
            ShopExecution se = null;
            try {
                se = shopServce.addShop(shop, shopImg.getInputStream(),shopImg.getOriginalFilename());
                if (se.getState()== ShopStateEnum.CHECK.getState()){
                    mapModel.put("success", true);
                    //注意是展示操作还是取操作 这里其实就是controller层的主要工作 把集合数组看为一个对象即可
                    List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
                    if (shopList == null || shopList.size() == 0){
                        shopList = new ArrayList<>();
                        shopList.add(se.getShop());
                        request.setAttribute("shopList",shopList );
                    }else {
                        //这里其实为了代码简洁可以合并 我这里为了便于理解没有合并
                        shopList.add(se.getShop());
                        request.setAttribute("shopList",shopList );
                    }

                }else {
                    mapModel.put("success",false );
                    mapModel.put("errMsg", se.getStateInfo());

                }
            } catch (IOException e) {
                mapModel.put("success",false );
                mapModel.put("errMsg", e.getMessage());
            }

            return mapModel;
        }else {
            mapModel.put("success",false );
            mapModel.put("errMsg","请输入店铺信息" );
            return mapModel;
        }

    }


    @Autowired
    private ShopCategoryService shopCategoryService;
    @Autowired
    private AreaService areaService;

    @GetMapping("/getshopinitinfo")
    @ResponseBody
    private Map<String,Object> getShopInitInfo(){
        Map<String,Object> modelMap = new HashMap<>();
        List<ShopCategory> shopCategoryList = new ArrayList<>();
        List<Area> areaList = new ArrayList<>();

        try {
          shopCategoryList =  shopCategoryService.getShopCategoryList(new ShopCategory());
          areaList =areaService.getAreaList();
          modelMap.put("shopCategoryList", shopCategoryList);
          modelMap.put("areaList", areaList);
          modelMap.put("success",true );

        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
        }
        return modelMap;
    }

    /**
     * 对前端页面展示做限定 店铺名称可以更改但是店铺分类不能更改
     * 这边首先实现的功能是根据shopId得到店铺信息
     */
    @GetMapping("/getshopbyid")
    @ResponseBody
    private Map<String,Object> getShopById(HttpServletRequest request){
//        Logger logger = LoggerFactory.getLogger(getShopById(request).getClass());
        Map<String,Object> modelMap = new HashMap<>();
        int shopId = HttpServletRequestUtil.getInt(request, "shopId");
        System.out.println(shopId);
//        logger.debug(String.valueOf(shopId));
        //从service层传过来的值都需要做非空判断才可以使用
        if (shopId > -1){
            //把放数据这一步放在try catch里面
            try {
                Shop shop = shopServce.getByShopId(shopId);
                modelMap.put("shop",shop );
                List<Area> areaList = areaService.getAreaList();
                //接下来把数组放进map集合
                modelMap.put("areaList", areaList);
                modelMap.put("success",true );
            } catch (Exception e) {
                modelMap.put("success", false);
                modelMap.put("errMsg",e.getMessage() );
            }
        }else {
            modelMap.put("success", false);
            modelMap.put("errMsg","empty shopId" );
        }
        return modelMap;
    }

    /**
     * 修改店铺信息 同注册店铺信息
     */
    @PostMapping("/modifyshop")
//    @GetMapping("/modifyshop")
    @ResponseBody
    private Map<String,Object> modifyShop(HttpServletRequest request){
        //这个变量是用来向前端传送数据的 这个跟之前倒是不一样
        Map<String,Object> mapModel = new HashMap<>();

        /**
         * 这里首先是验证码的判断
         */
//        if (!CodeUtil.checkVerifyCode(request)){
//            mapModel.put("success",false );
//            mapModel.put("errMsg","验证码输入错误" );
//            return mapModel;
//        }

        /**
         *   处理前端传来数据 上面@responsebody注解的作用是把object类转换为json
         *   下面这个配合依赖jackson-databind可以把前端传过来的字符串转换为object对象
         */
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        ObjectMapper mapper=new ObjectMapper();
        //创建这个的目的是用来接收前端传过来的实体类（转化好的）
        //在转化的时候可能会出现转化不了的情况 这个时候需要try catch
        Shop shop=null;
        try {
            shop=mapper.readValue(shopStr,Shop.class );
            System.out.println("========="+shop);
        } catch (IOException e) {
            mapModel.put("success",false );
            mapModel.put("errMsg", e.getMessage());
            return mapModel;
        }

        CommonsMultipartFile shopImg= null;
        CommonsMultipartResolver commonsMultipartResolver= new CommonsMultipartResolver(request.getServletContext());
        if (commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest= (MultipartHttpServletRequest) request;
            //这一步是从前端的file文件上口获取数据
            shopImg= (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }

        //修改店铺信息
        if (shop!=null&& shop.getShopId() !=null){
            ShopExecution se = null;
            try {
                if (shopImg == null){
                    se = shopServce.mpdifyShop(shop, null,null);
                }else {
                    se = shopServce.mpdifyShop(shop, shopImg.getInputStream(),shopImg.getOriginalFilename());
                }
                if (se.getState()== ShopStateEnum.SUCCESS.getState()){
                    mapModel.put("success", true);
                }else {
                    mapModel.put("success",false );
                    mapModel.put("errMsg", se.getStateInfo());

                }
            } catch (IOException e) {
                mapModel.put("success",false );
                mapModel.put("errMsg", e.getMessage());
            }

            return mapModel;
        }else {
            mapModel.put("success",false );
            mapModel.put("errMsg","请输入店铺id" );
            return mapModel;
        }

    }

    /**
     *待验证 因为没有网
     */

//    返回所属者所有的店铺信息
    @GetMapping("/getshoplist")
    @ResponseBody
    private Map<String,Object> getShopList(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        PersonInfo user = new PersonInfo();
        user.setUserId(8);
        user.setName("test");
        request.getSession().setAttribute("user",user );
        user  = (PersonInfo) request.getSession().getAttribute("user");

        try {
            Shop shopCondition = new Shop();
            shopCondition.setOwner(user);
            ShopExecution shopList = shopServce.getShopList(shopCondition, 0, 100);
            modelMap.put("shopList",shopList );
            modelMap.put("success",true );
            modelMap.put("user",user );
        } catch (Exception e) {
            modelMap.put("success",false );
            modelMap.put("errMsg",e.getMessage() );
        }
        return modelMap;

    }

    //获取店铺详情
    @GetMapping("/getshopmanagementinfo")
    @ResponseBody
    private Map<String,Object> getShopManagementInfo(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        int shopId = HttpServletRequestUtil.getInt(request, "shopId");
        if (shopId<=0){
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if (currentShopObj==null){
                //可以这样实现重定向 这个倒是不知道 查下modelmap的属性方法
//                地址已经修改
                modelMap.put("redirect",true );
                modelMap.put("url","/shopadmin/getshoplist" );
            }else {
                /**
                 * 这个地方的重定向地址有问题 待后面看下是定向到哪个路径
                 */
                Shop currentShop = (Shop) currentShopObj;
                modelMap.put("redirect",false );
                modelMap.put("shopId",currentShop.getShopId() );
            }
        }else {
            Shop shop =new Shop();
            shop.setShopId(shopId);
            request.getSession().setAttribute("currentShop",shop );
            modelMap.put("redirect",false );
        }
        return modelMap;
    }

    /**
     * 这里有一个小技巧 视频里页面跳转的开发是放在最后做的
     */



}

